package com.ricardoteix.subtitle {
	import com.ricardoteix.subtitle.events.FileParserEvent;
	import com.ricardoteix.subtitle.events.SubtitleEvent;
	import com.ricardoteix.subtitle.parsers.FileParser;
	import com.ricardoteix.utils.timer.ChronoTrigger;
	import com.ricardoteix.utils.timer.events.ChronoTriggerEvent;
	import flash.events.EventDispatcher;
	
	/**
	 * Provide an easy way to syncronize subtitle data from external files like srt format.
	 * ...
	 * @author Ricardo Teixeira
	 */
	public class Subtitle extends EventDispatcher {
		
		private var fileParser:FileParser;
		private var subtitleBlocks:Vector.<SubtitleBlock>;
		
		private var _paused:Boolean;
		
		private var urlSubtitle:String;
		private var chrono:ChronoTrigger;
		
		/**
		 * Class Contructor
		 * @param	url		File url to load
		 * @param	type	Type of subtitle format
		 * @see	SubtitleType
		 * @see	SubtitleBlock
		 * @see	SubtitleTime
		 * @see	SubtitleEvent
		 */
		public function Subtitle (url:String = "subtitles/andamento_wck.srt", type:String = "srt") {
			this.fileParser = new FileParser ();
			this.fileParser.addEventListener (FileParserEvent.PARSE_COMPLETE, onParseComplete);
			this.fileParser.parse (url, type);
		}
		
		private function onParseComplete(e:FileParserEvent):void {
			this.subtitleBlocks = e.blocks;
			this.chrono = new ChronoTrigger ();
			this.chrono.addEventListener (ChronoTriggerEvent.UPDATE, onChronoUpdate);
			this.chrono.start ();
		}
		
		private function onChronoUpdate(e:ChronoTriggerEvent):void {
			var chronoDate:Date = new Date (0, 0, 0, 0, 0, 0, e.time); 
						
			var evento:SubtitleEvent;
			for (var i:int = 0; i < this.subtitleBlocks.length; i++) {
				var block:SubtitleBlock = this.subtitleBlocks[i];
				if (block.startTime.date.time <= chronoDate.time) {
					evento = new SubtitleEvent (SubtitleEvent.ENTER_BLOCK, e.time, block);
				}
				if (block.endTime.date.time <= chronoDate.time) {
					evento = new SubtitleEvent (SubtitleEvent.EXIT_BLOCK, e.time, block);
					if (i == this.subtitleBlocks.length - 1) {
						this.dispatchEvent (new SubtitleEvent (SubtitleEvent.EOF, e.time));
					}
				}
			}
			
			if (evento != null) {
				this.dispatchEvent (evento);
			} 
			
			this.dispatchEvent (new SubtitleEvent (SubtitleEvent.UPDATE, e.time));
		}
		
		/**
		 * Toggle pause and play.
		 * @return
		 */
		public function togglePause ():void {
			this.chrono.togglePause ();
		}
		
		/**
		 * Atual state of subtitle update
		 * @return Boolean
		 */
		public function get paused():Boolean { return this.chrono.paused; }
		
		
	}

}